package com.exd.kafka.service;

import com.alibaba.fastjson2.JSONObject;
import com.exceeddata.ac.format.convert.CsvToVswConverter;
import com.exceeddata.sdk.vdata.data.VDataFrame;
import com.exceeddata.sdk.vdata.data.VDataReader;
import com.exceeddata.sdk.vdata.data.VDataRow;

import java.io.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

public class MockVdataCsvToVsw {

    public static List<String> mockCsvRow(String sinals, long time, long limit, int cycle) {
        DateFormat timeFormat = getZonedDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //信号时间格式化
        long startTime = time * 1000;

        int value = 90;

        String formatTime = "";
        StringBuilder sb;
        List<String> dataList = new ArrayList<>();
        dataList.add(sinals);
        for (long i = 0; i < limit; i++) {
            sb = new StringBuilder("");
            formatTime = timeFormat.format(startTime);
            sb.append(formatTime).append(",");
            if (i <= 12000) {
                sb.append(90);
            } else if (i > 12000 && i < 12038) {
                if (value < 128) {
                    value +=1;
                }
                sb.append(value);
            } else if (i >= 12038 && i < 30000){
                sb.append(90);
            } else {
                sb.append(130);
            }
            dataList.add(sb.toString());
            startTime += cycle;
        }
        return dataList;
    }

    public static void csvToVswFile(String csvFilePath, String vswFilePath) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(vswFilePath);
        CsvToVswConverter csvToVswConverter = new CsvToVswConverter();
        csvToVswConverter.setInputFile(csvFilePath);
        csvToVswConverter.setTimeColumnName("msg_time");
        csvToVswConverter.setOutputStream(fileOutputStream);
        csvToVswConverter.convert();
    }

    public static Long getLocalDateTimeSecond(LocalDateTime localDateTime){
        return localDateTime.toEpochSecond(ZoneOffset.of("+8"));
    }

    public static String headerToString(final List<String> cols, final StringBuilder sb) {
        sb.setLength(0);
        sb.append("msg_time");
        for (final String n : cols) {
            sb.append(',').append(n);
        }
        sb.append('\n');
        return sb.toString();
    }

    public static String rowToString(
            VDataRow row,
            StringBuilder sb,
            DateFormat timeFormat,
            DecimalFormat fmt) {
        sb.setLength(0);
        sb.append(timeFormat.format(row.getTime().toEpochMilli()));
        for (Object d: row.getValues()) {
            sb.append(',');
            if (d != null) {
                sb.append(fmt.format(d));
            }
        }
        sb.append('\n');
        return sb.toString();
    }

    public static void writerToFile(String vswData, String filename) throws Exception {
        DateFormat dateFormat = getZonedDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //信号时间格式化
        DecimalFormat decimalFormat = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); //信号时间格式化
        decimalFormat.setMaximumFractionDigits(10);

        byte[] vswByte = Base64.getDecoder().decode(vswData);

        FileWriter fileWriter = new FileWriter(filename);
        StringBuilder stringBuilder = new StringBuilder(4096);

        VDataRow row = null;
        VDataReader reader = new VDataReader(vswByte, null);
        VDataFrame df = reader.df();

        Iterator<VDataRow> iter = df.iterator(Integer.valueOf(1000));

        //header
        if (iter.hasNext()) {
            fileWriter.write(headerToString(df.cols(), stringBuilder));
        }

        //rows
        while (iter.hasNext()) {
            row = iter.next();
            fileWriter.write(rowToString(row, stringBuilder, dateFormat, decimalFormat));
        }

        fileWriter.flush();
        fileWriter.close();
    }

    public static byte[] readFromByteFile(String file) throws IOException {
        File filename = new File(file);
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] temp = new byte[1024];
        int size = 0;
        while((size = in.read(temp)) != -1){
            out.write(temp, 0, size);
        }
        in.close();
        return out.toByteArray();
    }

    public static DateFormat getZonedDateFormat(String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        TimeZone TIMEZONE = TimeZone.getTimeZone("Asia/Shanghai");
        dateFormat.setTimeZone(TIMEZONE);
        return dateFormat;
    }

    public static long writeCsvFile(File readFile, File writeFile, long time, int cycle) throws IOException {
        DateFormat timeFormat = getZonedDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //信号时间格式化
        BufferedReader br = new BufferedReader(new FileReader(readFile));
        BufferedWriter bw = new BufferedWriter(new FileWriter(writeFile));
        String line;
        long lineCount = 0;
        StringBuilder sb = null;
        long startTime = time;
        String formatTime = "";

        while (true) {
            formatTime = timeFormat.format(startTime);
            sb = new StringBuilder("");
            line = br.readLine();
            if (null == line) {
                break;
            }
            if (lineCount == 0) {
                sb.append("msg_time").append(line);
                lineCount ++;
            } else {
                sb.append(formatTime).append(line);
                startTime += cycle;
            }
            bw.write(new String(sb));
            bw.newLine();
        }
        bw.close();
        br.close();
        return startTime;
    }

    public static void main(String[] args) throws Exception {
        int second = 600;
        int cycle = 1;
        Long milliSecond = (getLocalDateTimeSecond(LocalDateTime.now()) - second) * 1000;
        String path = "/Users/zhaowei/Desktop/test/csv";

        String writePath =  path +"/" + milliSecond +"/";
        File writefile = new File(writePath);
        if (!writefile.exists()) {
            writefile.mkdirs();
        }

        Long time = milliSecond;
        System.out.println(milliSecond);

        List<String> fileList = Arrays.asList("0", "1", "2", "3");

        File[] files = new File(path).listFiles();
        for (File file : files) {
            if (file.getPath().endsWith(".csv")){
                for (String name : fileList) {
                    if (file.getName().contains(name)){
                        System.out.println(name);
                        String outPath = writePath + "alarm"+name + ".csv";
                        String vswPath = writePath + name + ".vsw";
                        File outFile = new File(outPath);
                        time = writeCsvFile(file, outFile, time, cycle);
                        csvToVswFile(outPath, vswPath);

                        byte[] vswBytes = readFromByteFile(vswPath);
                        String vswData = Base64.getEncoder().encodeToString(vswBytes);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("collectionTime", milliSecond);
                        jsonObject.put("data", vswData);
                        jsonObject.put("vin", "LDP91H964RE000135");
//                        System.out.println(jsonObject.toJSONString());

//                        writerToFile(vswData, writePath + name + ".csv");
                    }
                }
            }
        }
        System.out.println(time);
    }
}
